let cartItem = document.querySelector(".cart-item");
let qx = document.querySelector(".qx input");

let cartitem = document.querySelector(".cart-item");

// 获取去结算按钮
let pay = document.querySelector(".pay");

// 计算总价区域
let price = document.querySelector(".shopname span");

let token = localStorage.getItem("token");
let host = "http://127.0.0.1:1337";

let user = document.querySelector(".order-head-right .user");
// 获取用户名
let uinfoUrl = host + "/api/v1/user/info";
// 头部设置token参数
axios.defaults.headers.common["token"] = token;
let uname = axios.get(uinfoUrl);

uname.then(function(res) {
    let userName = res.data.data.userName;
    console.log(res.data.data);
    user.innerHTML = userName;
})


//购物车
let carsUrl = host + "/api/v1/shop_carts";
let objstatus = [];
async function render() {
    axios.defaults.headers.common["token"] = token;
    let p1cart = await axios.get(carsUrl);
    console.log(p1cart.data.data);
    let cartsArr = p1cart.data.data;
    let cartStr = cartsArr.map(item=> {
        if(item.product.coverImage.split("/")[1]=="uploads") {
            item.product.coverImage = host + item.product.coverImage;
       } 
        return  `
        <div class="item">
            <div class="sel">
                <input type="checkbox" shopId="${item.product.id}" shopCount="${item.amount}" coverImg = "${item.product.coverImage}" shopname="${item.product.name}" shopprice="${item.product.price}">
            </div>
            <div class="item-name">
                <img src="${item.product.coverImage}" alt="">
                <h3>${item.product.name}</h3>
            </div>
            <div class="item-price">
                <span>${item.product.price}</span>
            </div>
            <div class="item-amout">
                <div class="stepper">
                       <button class="stepper__button" onclick="clickremove(this,${item.product.price},${item.product.id})">-</button>
                       <div class="stepper__content">
                           <input type="text" class="stepper__input" value="${item.amount}" min="1" style="text-align: center;" onblur="changed(this,${item.amount},${item.product.id})"/>
                       </div>
                       <button class="stepper__button" onclick="clickadd(this,${item.product.price},${item.product.id})">+</button>
               </div>  
            </div>
            <div class="item-total">
                <span>${item.product.price * item.amount}</span>
            </div>
            <div class="item-opra">
               <span onclick="delcar(${item.id},this)">❌</span>
            </div>  
      </div>
   `
     }).join("");
     cartItem.innerHTML = cartStr;
     let sels = document.querySelectorAll(".sel input");

    //全选按钮
     qx.onchange = function() {
         let countPrice = 0; 
         sels.forEach(item=> {
             item.checked = this.checked;
            //每一个商品的小计价格
            if(this.checked) {
                let itemPrice = Number(item.parentElement.parentElement.querySelectorAll(".item-total span")[0].innerHTML) ;
                countPrice+=itemPrice; 
            } else {
                countPrice = 0;
            }
         })
         price.innerHTML = countPrice; 
     } 

    // 当刷新页面时如果单选按钮有一个没有选中那么就让全选按钮为false，定义状态变量sta
    let sta = true;
    for(let i=0;i<sels.length;i++) {
          if(sels[i].checked==false) {
              sta = false;
             //满足条件则自动退出循环
              break;
          }
    }
     qx.checked = sta;
     
    // 如果购物车为空的时候让全选按钮为false
     if(sels.length==0) {
        qx.checked = false;
        price.innerHTML = 0;
     } 

    //单选按钮
    for(let i=0;i<sels.length;i++) {
        sels[i].onchange = function() {
           let flag = true;
           let countPrice  = 0;
           for(let j=0;j<sels.length;j++) {
                if(!sels[j].checked) {
                    flag = false;
                } else {
                    let itemPrice = Number(sels[j].parentElement.parentElement.querySelectorAll(".item-total span")[0].innerHTML);
                    countPrice+=itemPrice;
                }
           }
           qx.checked = flag;
           price.innerHTML = countPrice;
        }
    }  
    // sels = Array.from(sels);
    // sels.splice(index,1);
    pay.onclick = function() {
        console.log("click");
        let shopArrcount = [];
        let shopinfo = [];
        for(let i=0;i<sels.length;i++) {
             if(sels[i].checked) {
                // 获取到商品的id和商品的数量
                let shopid = sels[i].getAttribute("shopId");
                let shopCount = sels[i].getAttribute("shopCount");
                let shopname  = sels[i].getAttribute("shopname");
                let coverImg = sels[i].getAttribute("coverImg");
                let shopprice  = sels[i].getAttribute("shopprice");
                console.log(shopid,shopCount);
                let obj2 = {product:shopid,amount:shopCount};
                let obj = {product:shopid,amount:shopCount,name:shopname,coverImage:coverImg,price:shopprice};
                shopArrcount.push(obj2);
                shopinfo.push(obj);
                localStorage.setItem("shopcount",JSON.stringify(shopArrcount));
                localStorage.setItem("shopInfo",JSON.stringify(shopinfo));
                location.href = "order.html"
             } 
        }
    }
    let shopitem = document.querySelectorAll(".cart-item .item");
    // 如果购物车为空的话那么就让去结算按钮消失
    if(shopitem.length==0) {
        pay.style.display = "none";
    } else {
        pay.style.display = "block";
    }
}

render();

async function clickadd(btn,pri,product) {
    let value =  btn.previousElementSibling.children[0].value;
    let span = btn.parentElement.parentElement.parentElement.querySelector(".item-total span");
    let parele = btn.parentElement.parentElement.parentElement;

    let caraddUrl = host + "/api/v1/shop_carts";
    // product:商品id
    let addData = {product,amount:1};
    // 头部设置token参数
    axios.defaults.headers.common["token"] = token;
    let p2add =await axios.post(caraddUrl,addData);
    value++;
    span.innerHTML = value*pri;
    if(value>1) {
        btn.previousElementSibling.previousElementSibling.disabled = false;
    }
    btn.previousElementSibling.children[0].value = value;

    totalPrice(parele,total=0)
}

async function clickremove(btn,pri,product) {
    let value =  btn.nextElementSibling.children[0].value;
    let span = btn.parentElement.parentElement.parentElement.querySelector(".item-total span");
    let parele = btn.parentElement.parentElement.parentElement;

    console.log(pri);
    // console.log(yeye);
    if(value==1) {
        btn.disabled = true;
    } else {
        btn.disabled = false;
        value--;
        span.innerHTML = value*pri;
        console.log(span);

      let caraddUrl = host + "/api/v1/shop_carts";
      // product:商品id 
      let addData = {product,amount:-1};
      // 头部设置token参数
      axios.defaults.headers.common["token"] = token;
      let p2add =await axios.post(caraddUrl,addData);
    }
    btn.nextElementSibling.children[0].value = value;

    totalPrice(parele,total=0)
}


// 鼠标失去焦点时候购物车的数量发生变化
async function changed(ipt,count,product) {
     console.log(ipt.value);
     let caraddUrl = host + "/api/v1/shop_carts";
     console.log(count);
    //  product:商品id 
    if(ipt.value<count) {
        var addData = {product,amount:-(count-ipt.value)};
    } else {
        var addData  = {product,amount:(ipt.value-count)};
    }
     //头部设置token参数
     axios.defaults.headers.common["token"] = token;
     let p2add =await axios.post(caraddUrl,addData);
     //获取购物车单独行
     let parele = ipt.parentElement.parentElement.parentElement.parentElement;

    // 获取该行单价 
    let uniprice = Number(parele.querySelector(".item-price span").innerHTML);
    let coutprice = parele.querySelector(".item-total span");
    coutprice.innerHTML = Number(ipt.value) * uniprice;
    totalPrice(parele,total=0)
}

// 删除按钮
async function delcar(shopid,btn) {
     let delshopUrl =  host + `/api/v1/shop_carts/${shopid}`;
     axios.defaults.headers.common["token"] = token;
     let p3del = await axios.delete(delshopUrl);
    //  计算删除以后的商品总价
     let total = 0;
    // 购物车的单独行  删除dom元素
    let item = btn.parentElement.parentElement;
    let par = btn.parentElement.parentElement.parentElement;
    let btns  = Array.from(par.querySelectorAll(".item-opra span"));
    // 获得删除项的索引值
    let index = btns.findIndex(item=> {
           return item==btn;
    });
    // 删除后所有的复选框
    let sels = item.parentElement.querySelectorAll(".sel input");
    item.remove();

    sels = Array.from(sels);
    sels.splice(index,1);
   
    let flag = true;
    for(let i=0;i<sels.length;i++) {
        if(sels[i].checked==false) {
            flag = false;
            break;
        }
    }
    if(sels.length==0) {
        flag = false;
        price.innerHTML = 0;
    }
    qx.checked = flag;
    let allchk = par.querySelectorAll(".sel input");
    // console.log(sels);
    console.log(allchk);
    for(let i=0;i<allchk.length;i++) {
        if(allchk[i].checked) {
            total += Number(allchk[i].parentElement.parentElement.querySelector(".item-total span").innerHTML);
        }
   }
   price.innerHTML = total;
    
    // console.log(sels);
}

// 给total默认值0
function totalPrice(parele,total=0) {
      // ele为当前触发元素的最外层父级元素
      let yeye =  parele.parentElement;
       //获取所有的复选框
      allchk = yeye.querySelectorAll(".sel input");
      for(let i=0;i<allchk.length;i++) {
        if(allchk[i].checked) {
            total += Number(allchk[i].parentElement.parentElement.querySelector(".item-total span").innerHTML);
        }
   }
   price.innerHTML = total;
}













